package news

import (
	"gin/common/lib/gorm"
	"gin/dao/entity"
	"gin/model/body"
	gorm2 "gorm.io/gorm"
)

// Add 发布动态
func Add(p body.AddNewsParam) {
	gorm.GinDb.Table("cmf_users_news").Create(&p)
}

// Update 修改动态
func Update(p body.UpdateNewsParam) {
	gorm.GinDb.Table("cmf_users_news").Where("id = ?", p.Id).Updates(&p)
}

func List(p body.NewsListParam) ([]*entity.UsersNewsDetail, int64) {
	var list []*entity.UsersNewsDetail
	db := gorm.GinDb.Table("cmf_users_news n").Select("n.*,u.user_nickname,u.avatar")
	db.Joins("left join cmf_users u on u.id = n.uid")
	db = generateQueryWrapper(p, db)
	switch p.OrderType {
	case 1:
		db.Order("create_at desc")
	case 2:
		db.Order("(like_num+comment_num) desc")
	case 3:
		db.Order("read_num desc")
	}
	db.Offset(p.GetOffset()).Limit(p.GetLength()).Find(&list)
	return list, ListCount(p)
}

func ListCount(p body.NewsListParam) (count int64) {
	db := gorm.GinDb.Table("cmf_users_news")
	generateQueryWrapper(p, db).Count(&count)
	return
}

// Del 删除动态
func Del(uid, id int64) {
	gorm.GinDb.Table("cmf_users_news").Where("uid = ? and id = ?", uid, id).Update("disabled", 1)
}

// Detail 获取动态详情
func Detail(id int64) entity.UsersNews {
	var detail entity.UsersNews
	gorm.GinDb.Table("cmf_users_news").Where("id = ?", id).Find(&detail)
	return detail
}

// UserNewNews 获取用户最新动态
func UserNewNews(uid int64) entity.UsersNews {
	var detail entity.UsersNews
	gorm.GinDb.Table("cmf_users_news").Where("uid = ?", uid).
		Order("id desc").Limit(1).Find(&detail)
	return detail
}

// UpdateNum 修改动态数量参数
func UpdateNum(id int64, genre byte, increase bool) {
	db := gorm.GinDb.Table("cmf_users_news").Where("id = ?", id)
	switch genre {
	case 1:
		db.UpdateColumn("read_num", gorm2.Expr("read_num + ?", 1))
	case 2:
		if increase {
			db.UpdateColumn("like_num", gorm2.Expr("like_num + ?", 1))
		} else {
			db.UpdateColumn("like_num", gorm2.Expr("like_num - ?", 1))
		}
	case 3:
		if increase {
			db.UpdateColumn("comment_num", gorm2.Expr("comment_num + ?", 1))
		} else {
			db.UpdateColumn("comment_num", gorm2.Expr("comment_num - ?", 1))
		}
	}

}

// 组装查询条件
func generateQueryWrapper(p body.NewsListParam, db *gorm2.DB) *gorm2.DB {
	if len(p.Uid) > 0 {
		db.Where("uid in ?", p.Uid)
	}
	db.Where("disabled = 0")
	return db
}
